package userservice

import (
	"model/usermodel"
	"services"
	"time"
	"math/rand"
	"fmt"
	"model/mshandler"
	"github.com/lexkong/log"
)

//注册
func Register(phoneNumber string, userName string, email string, password string) services.Response {
	ms, err := usermodel.GetRgSmsFromRds(phoneNumber)
	if err != nil {
		return responseFail("验证码无效,请重试")
	}
	//计算验证码是否过期
	redisTime := time.Unix(ms.Timestamp, 0)
	nowTime := time.Unix(time.Now().Unix(), 0)
	countTime := nowTime.Sub(redisTime).Minutes()
	if countTime > 300 {
		return responseFail("验证码无效,请重试")

	}
	if userName == "" {
		return responseFail("用户名不能为空")

	}

	if phoneNumber == "" {
		return responseFail("手机号不能为空")

	}
	if email == "" {
		return responseFail("邮箱不能为空")

	}
	if password == "" {
		return responseFail("密码不能为空")

	}

	if usermodel.CheckUserNameExisted(userName) {
		return responseFail("用户名已注册")

	}
	if usermodel.CheckPhoneExisted(phoneNumber) {
		return responseFail("手机号已注册")

	}
	if usermodel.CheckEmailExisted(email) {
		return responseFail("邮箱已注册")

	}
	user := &usermodel.UserInfo{Name: userName, Password: password, Phone: phoneNumber, Email: email}
	if usermodel.CreateUserInfo(user) {
		return services.Response{
			Code:    200,
			Success: true,
			Message: "注册成功",
			Data:    nil,
		}
	} else {
		return responseFail("注册失败")
	}
}

func responseFail(message string) services.Response {
	return services.Response{
		Code:    200,
		Success: false,
		Message: message,
		Data:    nil,
	}
}

/**
 重置密码
 */
func ResetPassword(smsCode string, phoneNumber string, newPassword string) services.Response {
	ms, err := usermodel.GetRgSmsFromRds(phoneNumber)
	if err != nil {
		return responseFail("验证码无效,请重试")

	}
	//计算验证码是否过期
	redisTime := time.Unix(ms.Timestamp, 0)
	nowTime := time.Unix(time.Now().Unix(), 0)
	countTime := nowTime.Sub(redisTime).Minutes()
	if countTime > 3000 {
		return responseFail("验证码无效,请重试")

	}
	if smsCode != ms.SmsCode {
		return responseFail("验证码错误,请重试")

	}
	user := usermodel.QueryIdByPhone(phoneNumber)
	if user == nil {
		return responseFail("查无此人")

	}
	if usermodel.ResetPassword(user.Id, newPassword) {
		return services.Response{
			Code:    200,
			Success: true,
			Message: "修改成功",
			Data:    nil,
		}
	} else {
		return responseFail("修改失败")
	}
}

/**
	注册时发送短信
 */
func SendRegisterSmsCode(phoneNumber string) services.Response {
	//生成短讯
	rnd := rand.New(rand.NewSource(time.Now().UnixNano()))
	smsCode := fmt.Sprintf("%06v", rnd.Int31n(1000000))
	//发送
	response, err := mshandler.SendMs(phoneNumber, smsCode)
	//发送失败返回
	if err != nil {
		return services.Response{
			Code:    200,
			Success: false,
			Message: "验证码发送失败",
			Data:    nil,
		}
	}
	smsResponse := usermodel.CheckSendSmsRespose{smsCode, time.Now().Unix()}
	m, err := usermodel.SetRgSmsToRds(phoneNumber, smsResponse)
	if err != nil {
		log.Logger.Info(err.Error())
	}
	log.Logger.Info(m)
	//发送成功返回
	return services.Response{
		Code:    200,
		Success: true,
		Message: "验证码发送成功",
		Data:    response,
	}

}
